#!/use/bin/python
# coding=utf-8
# 数据分析-助眠功能-活跃率
import datetime
import pymysql
from dateutil.relativedelta import relativedelta

from dbutils.pooled_db import PooledDB


# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    # pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.150.109', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.151.80', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',port=3306)  # 1为连接池里的最少连接数

    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

#根据传入的SQL 返回执行SQL返回的数量
def selectNumBySql(sql):
    conn, cur = getDataConnection()
    #print(sql)
    cur.execute(sql)
    numResult = cur.fetchone()
    num = 0
    if numResult is not None:
        num = numResult[0]
    if num is None:
        return 0
    return num

#计算百分比 保留两位小数  如:34.88%
# X为分子 Y为分母
def getRateByXY(X,Y):
    rate = 0
    if(X is None or Y is None):
        return rate
    if Y != 0:
        if X > Y:
            rate = 100
        else:
            rate = round(X / Y, 4) * 100
    return rate

# 记录 助眠功能活跃率-日活率  analysis_zmgn_active_rate     每天
def insertActiveRateDay(today):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_zmgn_active_rate 表是否已经存在当天 数据
        countNum = selectNumBySql(
            f"select count(1) num from analysis_zmgn_active_rate t where 1=1 and t.ref_date =  '{today}'")
        # 获取助眠功能-近30天内累计活跃用户数
        actvieNum30D = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) device_num from log_analysis t where 1=1 and create_time >= DATE_SUB(NOW(), INTERVAL 30 DAY)")
        # 获取助眠功能-近7天内日均活跃用户数
        actvieNum1D = selectNumBySql(
            f"select count(1)/7 device_num from log_analysis t where 1=1 and create_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)")
        activeRateDay = getRateByXY(actvieNum1D, actvieNum30D)

        if countNum == 0:
            logDetail = f"新增-{today}日-助眠功能活跃率,近30天内累计活跃用户数为{actvieNum30D},近7天内日均活跃用户数为{actvieNum1D},日活率为{activeRateDay}"
            print(logDetail)
            # 插入
            insertSql = f"""insert into analysis_zmgn_active_rate(30d_actvie_num,1d_actvie_num,day_active_rate,ref_date) 
                value({actvieNum30D},{actvieNum1D},{activeRateDay},'{today}')"""
            cur.execute(insertSql)
        else:
            logDetail = f"更新-{today}日-助眠功能活跃率,近30天内累计活跃用户数为{actvieNum30D},近7天内日均活跃用户数为{actvieNum1D},日活率为{activeRateDay}"
            print(logDetail)
            # 更新
            updateSql = f"""
                update analysis_zmgn_active_number set 30d_actvie_num = {actvieNum30D},1d_actvie_num = {actvieNum1D},day_active_rate = {activeRateDay} ,update_time = now()  where  ref_date = '{today}'
            """
            cur.execute(updateSql)
        saveLog(logDetail, today)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

# 获取当前日期
def todayYMD():
    today = datetime.datetime.now()-1
    # 获取想要的日期的时间
    re_date = (today).strftime('%Y-%m-%d')
    return re_date


# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getMonthdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m')
    return re_date

# 获取上一个月
def getBeforeMonth(d):
    today = datetime.datetime.now()
    re_date = (today + relativedelta(months=-d)).strftime("%Y-%m")
    return re_date

# 获取上一个年当月
def getBeforeYear():
    today = datetime.datetime.now()
    re_date = (today + relativedelta(years=-1)).strftime("%Y-%m")
    return re_date

#如 2022年12月13号 获取 221213 作为分表后缀
def getdateyyMMdd(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y%m%d')
    re_date = re_date[2:]
    return re_date

def saveLog(detail,ref_date):
    try:
        conn, cur = getDataConnection()
        jobId = 95
        jobName = '核心指标-助眠功能-活跃率'
        tableName = 'analysis_zmgn_active_rate'
        # 插入日志表
        saveLogSql = """insert into log_xxljob_analysis (job_id,job_name,detail,table_name,ref_date) 
                value(%s,'%s','%s','%s','%s')""" % (jobId,jobName,detail,tableName,ref_date)
        cur.execute(saveLogSql)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

if __name__ == '__main__':
    d = 1
    today = getdate(d)
    print(f"{today}日期,执行<助眠功能-活跃率>报表")
    insertActiveRateDay(today)

